//
//
//package com.gen;
//
//import cn.hutool.core.util.StrUtil;
//import com.baomidou.mybatisplus.core.toolkit.StringUtils;
//import com.baomidou.mybatisplus.generator.config.InjectionConfig;
//import com.baomidou.mybatisplus.generator.config.StrategyConfig;
//import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
//import com.baomidou.mybatisplus.generator.config.builder.Entity;
//import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
//import com.dto.BasePageQuery;
//import com.dto.BizBaseHeadDto;
//import com.entity.BizBaseHeadEntity;
//import com.gen.config.MbpGeneratorConfig;
//import com.vo.BizBaseHeadVo;
//
//import java.util.*;
//
///**
// * @author: Cxx
// * @Version 1.0
// * @create: 2025-10-01 21:32
// * @description:
// **/
//public class MbpGeneratorHead extends MbpGenerator {
//
//    private Entity entity;
//
//    public MbpGeneratorHead(MbpGeneratorConfig config) {
//        super(config);
//    }
//
//    @Override
//    public void strategyConfigAfter(StrategyConfig.Builder builder) {
//        builder
//                .entityBuilder().superClass(BizBaseHeadEntity.class);
//        this.entity = builder
//                .entityBuilder().build().entity();
//    }
//
//    @Override
//    public List<String> getTableNames() {
//        return Collections.singletonList(getConfig().getHeadTableName());
//    }
//
//
//    @Override
//    public void injectionConfig(InjectionConfig.Builder builder) {
//
//        // 自定义参数
//        Map<String, Object> customMap = new HashMap<>();
//        customMap.put("dtoPackageName", getConfig().getParent() + ".dto");
//        customMap.put("dtoSuperClass", BizBaseHeadDto.class.getCanonicalName());
//        customMap.put("pageReqDtoSuperClass", BasePageQuery.class.getCanonicalName());
//
//        customMap.put("voPackageName", getConfig().getParent() + ".vo");
//        customMap.put("voSuperClass", BizBaseHeadVo.class.getCanonicalName());
//
//        StringJoiner itemDtoJoiner = new StringJoiner("\r\n");
//        StringJoiner itemVoJoiner = new StringJoiner("\r\n");
//
//        List<String> itemTableNames = getConfig().getItemTableNames();
//        for (String itemTableName : itemTableNames) {
//            String propName = processName(itemTableName, entity.getNaming(), Set.of(StrUtil.emptyToDefault(getConfig().getTablePrefix(), "").split(",")), Collections.emptySet());
//            String entityName = NamingStrategy.capitalFirst(propName);
//            entityName = entity.getConverterFileName().convert(entityName);
//            System.out.println("entityName = " + entityName);
//            itemDtoJoiner.add("private List<" + getConfig().getParent() + ".dto." + entityName + "DTO> " + propName + "List;");
//            itemVoJoiner.add("private List<" + getConfig().getParent() + ".vo." + entityName + "VO> " + propName + "List;");
//        }
//        customMap.put("dtoProperties", itemDtoJoiner.toString());
//        customMap.put("voProperties", itemVoJoiner.toString());
//
//        builder.customMap(customMap);
//
//        // 自定义模板
//        List<CustomFile> customFiles = new ArrayList<>();
//        customFiles.add(new CustomFile.Builder().packageName("dto").fileName("DTO.java")
//                .templatePath("/templates/dto.java.vm").enableFileOverride().build()
//        );
//
//        customFiles.add(new CustomFile.Builder().packageName("dto").fileName("PageReqDTO.java")
//                .templatePath("/templates/pageReqDTO.java.vm").enableFileOverride().build()
//        );
//        customFiles.add(new CustomFile.Builder().packageName("dto").fileName("SaveReqDTO.java")
//                .templatePath("/templates/saveReqDTO.java.vm").enableFileOverride().build()
//        );
//        customFiles.add(new CustomFile.Builder().packageName("dto").fileName("RespDTO.java")
//                .templatePath("/templates/respDTO.java.vm").enableFileOverride().build()
//        );
//
//        customFiles.add(new CustomFile.Builder().packageName("vo").fileName("PageReqVO.java")
//                .templatePath("/templates/pageReqVO.java.vm").enableFileOverride().build()
//        );
//        customFiles.add(new CustomFile.Builder().packageName("vo").fileName("SaveReqVO.java")
//                .templatePath("/templates/saveReqVO.java.vm").enableFileOverride().build()
//        );
//        customFiles.add(new CustomFile.Builder().packageName("vo").fileName("RespVO.java")
//                .templatePath("/templates/respVO.java.vm").enableFileOverride().build()
//        );
//
//        customFiles.add(new CustomFile.Builder().packageName("vo").fileName("VO.java")
//                .templatePath("/templates/vo.java.vm").enableFileOverride().build()
//        );
//
//        builder.customFile(customFiles);
//
//    }
//
//    private String processName(String name, NamingStrategy strategy, Set<String> prefix, Set<String> suffix) {
//        String propertyName = name;
//        // 删除前缀
//        if (prefix.size() > 0) {
//            propertyName = NamingStrategy.removePrefix(propertyName, prefix);
//        }
//        // 删除后缀
//        if (suffix.size() > 0) {
//            propertyName = NamingStrategy.removeSuffix(propertyName, suffix);
//        }
//        if (StringUtils.isBlank(propertyName)) {
//            throw new RuntimeException(String.format("%s 的名称转换结果为空，请检查是否配置问题", name));
//        }
//        // 下划线转驼峰
//        if (NamingStrategy.underline_to_camel.equals(strategy)) {
//            return NamingStrategy.underlineToCamel(propertyName);
//        }
//        return propertyName;
//    }
//}










package com.gen;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.builder.Entity;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.dto.BasePageQuery;
import com.dto.BizBaseHeadDto;
import com.entity.BizBaseHeadEntity;
import com.gen.config.MbpGeneratorConfig;
import com.vo.BizBaseHeadVo;

import java.util.*;

/**
 * MyBatis Plus 代码生成器 - 头部实体生成器
 *
 * @author: Cxx
 * @Version 1.0
 * @create: 2025-10-01 21:32
 * @description: 用于生成主表相关的DTO、VO等文件
 */
public class MbpGeneratorHead extends MbpGenerator {

    private Entity entity;
    private static final String DTO_PACKAGE = "dto";
    private static final String VO_PACKAGE = "vo";

    public MbpGeneratorHead(MbpGeneratorConfig config) {
        super(config);
    }

    @Override
    public void strategyConfigAfter(StrategyConfig.Builder builder) {
        // 设置实体类的父类
        builder.entityBuilder().superClass(BizBaseHeadEntity.class);
        this.entity = builder.entityBuilder().build().entity();
    }

    @Override
    public List<String> getTableNames() {
        // 只生成主表对应的文件
        return Collections.singletonList(getConfig().getHeadTableName());
    }

    @Override
    public void injectionConfig(InjectionConfig.Builder builder) {
        // 1. 准备自定义参数
        Map<String, Object> customMap = prepareCustomMap();

        // 2. 生成DTO和VO属性
        generateDtoAndVoProperties(customMap);

        // 3. 设置自定义参数
        builder.customMap(customMap);

        // 4. 添加自定义文件模板
        builder.customFile(prepareCustomFiles());
    }

    /**
     * 准备自定义参数映射
     */
    private Map<String, Object> prepareCustomMap() {
        Map<String, Object> customMap = new HashMap<>();
        String parentPackage = getConfig().getParent();

        // DTO相关参数
        customMap.put("dtoPackageName", parentPackage + ".dto");
        customMap.put("dtoSuperClass", BizBaseHeadDto.class.getCanonicalName());
        customMap.put("pageReqDtoSuperClass", BasePageQuery.class.getCanonicalName());

        // VO相关参数
        customMap.put("voPackageName", parentPackage + ".vo");
        customMap.put("voSuperClass", BizBaseHeadVo.class.getCanonicalName());

        return customMap;
    }

    /**
     * 生成DTO和VO属性
     */
    private void generateDtoAndVoProperties(Map<String, Object> customMap) {
        StringBuilder dtoProperties = new StringBuilder();
        StringBuilder voProperties = new StringBuilder();

        String parentPackage = getConfig().getParent();
        String tablePrefix = StrUtil.emptyToDefault(getConfig().getTablePrefix(), "");
        Set<String> prefixSet = new HashSet<>(Arrays.asList(tablePrefix.split(",")));

        for (String itemTableName : getConfig().getItemTableNames()) {
            String propName = processName(itemTableName, entity.getNaming(), prefixSet, Collections.emptySet());
            String entityName = entity.getConverterFileName().convert(NamingStrategy.capitalFirst(propName));

            // DTO属性: private List<com.example.dto.DeptDTO> deptList;
            String dtoField = String.format(
                    "private List<%s.dto.%sDTO> %sList;",
                    parentPackage, entityName, propName
            );
            dtoProperties.append(dtoField).append("\r\n");

            // VO属性: private List<com.example.vo.DeptVO> deptList;
            String voField = String.format(
                    "private List<%s.vo.%sVO> %sList;",
                    parentPackage, entityName, propName
            );
            voProperties.append(voField).append("\r\n");
        }

        customMap.put("dtoProperties", dtoProperties.toString());
        customMap.put("voProperties", voProperties.toString());
    }

    /**
     * 处理表名转换为属性名
     */
    private String processName(String name, NamingStrategy strategy, Set<String> prefix, Set<String> suffix) {
        String propertyName = name;

        // 删除前缀
        if (!prefix.isEmpty()) {
            propertyName = NamingStrategy.removePrefix(propertyName, prefix);
        }

        // 删除后缀
        if (!suffix.isEmpty()) {
            propertyName = NamingStrategy.removeSuffix(propertyName, suffix);
        }

        // 验证处理后的名称
        if (StringUtils.isBlank(propertyName)) {
            throw new IllegalArgumentException(
                    String.format("表名 '%s' 转换结果为空，请检查表前缀配置", name)
            );
        }

        // 下划线转驼峰命名
        if (NamingStrategy.underline_to_camel.equals(strategy)) {
            return NamingStrategy.underlineToCamel(propertyName);
        }

        return propertyName;
    }

    /**
     * 准备自定义文件模板配置
     */
    private List<CustomFile> prepareCustomFiles() {
        List<CustomFile> customFiles = new ArrayList<>();

        // 添加DTO模板
        addDtoTemplates(customFiles);

        // 添加VO模板
        addVoTemplates(customFiles);

        return customFiles;
    }

    /**
     * 添加DTO模板配置
     */
    private void addDtoTemplates(List<CustomFile> customFiles) {
        // DTO模板
        customFiles.add(createCustomFile(DTO_PACKAGE, "DTO.java", "/templates/dto.java.vm"));

        // 分页请求DTO
        customFiles.add(createCustomFile(DTO_PACKAGE, "PageReqDTO.java", "/templates/pageReqDTO.java.vm"));

        // 保存请求DTO
        customFiles.add(createCustomFile(DTO_PACKAGE, "SaveReqDTO.java", "/templates/saveReqDTO.java.vm"));

        // 响应DTO
        customFiles.add(createCustomFile(DTO_PACKAGE, "RespDTO.java", "/templates/respDTO.java.vm"));
    }

    /**
     * 添加VO模板配置
     */
    private void addVoTemplates(List<CustomFile> customFiles) {
        // VO模板
        customFiles.add(createCustomFile(VO_PACKAGE, "VO.java", "/templates/vo.java.vm"));

        // 分页请求VO
        customFiles.add(createCustomFile(VO_PACKAGE, "PageReqVO.java", "/templates/pageReqVO.java.vm"));

        // 保存请求VO
        customFiles.add(createCustomFile(VO_PACKAGE, "SaveReqVO.java", "/templates/saveReqVO.java.vm"));

        // 响应VO
        customFiles.add(createCustomFile(VO_PACKAGE, "RespVO.java", "/templates/respVO.java.vm"));
    }

    /**
     * 创建自定义文件配置
     */
    private CustomFile createCustomFile(String packageName, String fileName, String templatePath) {
        return new CustomFile.Builder()
                .packageName(packageName)
                .fileName(fileName)
                .templatePath(templatePath)
                .enableFileOverride()
                .build();
    }
}